from fastapi import Request, HTTPException
from fastapi.routing import APIRoute
from fastapiApp.controllers.user_control import get_username_token
from fastapi import Request, HTTPException

# 使用统一的日志配置
from fastapiApp.setting.logger_config import get_audit_logger

logger = get_audit_logger()

class AuthRequiredRoute(APIRoute):
    """自定义路由类，为所有非token获取的API添加token验证"""
    def get_route_handler(self):
        original_route_handler = super().get_route_handler()

        async def custom_route_handler(request: Request):
            # 跳过获取token的API
            if request.url.path.endswith("/access_token") and request.method == "POST":
                return await original_route_handler(request)

            # 检查请求中是否包含token参数
            token = request.query_params.get("token")

            if not token:
                logger.warning(f"请求 {request.url.path} 中未提供token参数")
                raise HTTPException(
                    status_code=401,
                    detail="未提供token参数，访问被拒绝"
                )

            # 验证token是否有效
            username = get_username_token(token)
            if not username:
                logger.warning(f"请求 {request.url.path} 中包含无效的token: {token}")
                raise HTTPException(
                    status_code=401,
                    detail="无效的token，访问被拒绝"
                )

            logger.debug(f"Token验证成功，用户: {username}，路径: {request.url.path}")
            # 将用户名添加到请求状态中，供后续处理使用
            request.state.username = username

            return await original_route_handler(request)

        return custom_route_handler

def setup_global_auth(app):
    """设置全局认证，为所有v1路由添加token验证"""
    # 为每个已注册的v1路由设置自定义路由类
    for route in app.routes:
        # 检查是否为v1下的API路由（排除文档和静态文件路由）
        if (isinstance(route, APIRoute) and
            route.path.startswith("/api/v1/") and
            not (route.path.endswith("/access_token") and route.methods == {"POST"})):
            route.route_class = AuthRequiredRoute
